package com.luo.controller;

import com.alibaba.fastjson.JSON;
import com.luo.model.ResultObj;
import com.luo.model.User;
import com.luo.service.UserService;
import com.luo.util.RedisUtil;
import com.luo.util.UsersMap;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 功能：管理员登录
 * 作者：Luo。
 * 日期：2024/1/25 11:38
 */
@WebServlet("/AdminLogin")
public class AdminLoginController extends HttpServlet {

    UserService userService = new UserService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ResultObj resultObj = new ResultObj();
        //获取用户名密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //根据用户名密码到数据库查询是否有该用户
        User userByUserNameAndPassWord = userService.queryUserByUserNameAndPassWord(user);
        //如果失败则发送登录失败
        if (userByUserNameAndPassWord == null) {
            resultObj.setCode("-2");
            resultObj.setMsg("登录失败");
            String jsonString = JSON.toJSONString(resultObj);
            resp.getWriter().write(jsonString);
            return;
        }
        //如果登录成功将token和对象保存到redis起来
        // 连接到Redis
        Jedis jedis = RedisUtil.getJedis();
        //生成token
        UUID uuid = UUID.randomUUID();
        String token = uuid.toString().replace("-", "");
        //设置存储信息
        Map<String, String> hashData = new HashMap<>();
        hashData.put("username", userByUserNameAndPassWord.getUsername());
        hashData.put("id", String.valueOf(userByUserNameAndPassWord.getId()));
        hashData.put("currentTime", String.valueOf(System.currentTimeMillis()));
        hashData.put("token", token);
        // 设置token值到Redis
        jedis.hmset(token, hashData);
        jedis.expire(token, 3600);
        // 关闭Redis连接
        jedis.close();
        resultObj.setCode("1");
        resultObj.setMsg("登录成功");
        resultObj.setResult(token);
        String jsonString = JSON.toJSONString(resultObj);
        resp.getWriter().write(jsonString);
    }
}
